<?php


namespace app\cms\model;


use app\cms\community\lib\modelData;
use app\cms\community\lib\QueryModel;
use app\cms\dto\replyInfo;
use iflow\Response;
use iflow\Utils\basicTools;
use think\facade\Db;
use think\model\relation\HasOne;

class replyModel extends QueryModel
{
    protected $table = "reply_table";

    /**
     * 添加评论
     * @param replyInfo $replyInfo
     * @return Response
     * @throws \Exception
     */
    public static function addReply(replyInfo $replyInfo): Response
    {
        $replyInfo -> reply_id = (new basicTools()) -> create_uuid();
        $reply = (array) $replyInfo;
        $reply['uid'] = session('userInfo')['uid'];

        $inc = (new modelData())
            -> setFormId($replyInfo -> form_id)
            -> modelFieldIncOrDec('reply_count', $replyInfo -> col_uuid, 1, 'inc');

        if (is_string($inc)) {
            return message() -> parameter_error($inc);
        }

        return message() -> success('评论成功', self::create($reply) -> toArray());
    }

    /**
     * 获取评论数据
     * @param int $form_id
     * @param int $id
     * @return Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getReplyList(int $form_id, int $id): Response
    {
        $model = (new formModel) -> getForm($form_id);
        if ($model) {

            // 获取指定模型数据
            $model = Db::connect($this->getConnection())
                -> name($model['form_name']) -> where([
                    'id' => $id
                ]) -> find();

            // 验证模型是否存在
            if ($model) {
                if (intval($model['reply_enable']) !== 1) return message() -> unauthorized_error('该内容评论未开启');
                $reply = $this->where([
                    'col_uuid' => $model['uuid'],
                    'parent_id' => '-1'
                ]) -> withJoin([
                    'hasUser' => [
                        'nick_name' => 'nick_name',
                        'avatar' => 'avatar',
                        'signature' => 'signature'
                    ]
                ], 'LEFT') -> paginate([
                    'page' => request() -> getParams('page'),
                    'list_rows' => 12
                ]);
                $items = $reply -> items();
                $replyList = [];
                if ($items) {
                    foreach ($items as $key => $value) {
                        $replyList[] = array_merge($value -> toArray(), [
                            'children' => $this->getChildrenReply($value['reply_id'])
                        ]);
                    }
                    return message() -> success('获取评论数据成功', $replyList, [
                        'page' => $reply -> lastPage(),
                        'count' => $reply -> total()
                    ]);
                }
            }
        }
        return message() -> nodata('暂无评论数据');
    }

    public function hasUser(): HasOne
    {
        return $this->hasOne(userModel::class, 'uid', 'uid');
    }

    private function getChildrenReply(string $parentId): array
    {
        if ($parentId === 0) return [];
        $nav = $this->where([
            'parent_id' => $parentId
        ]) -> withJoin([
            'hasUser' => [
                'user_name' => 'user_name',
                'avatar' => 'avatar',
                'signature' => 'signature'
            ]
        ], 'LEFT') -> select() -> toArray();
        $items = [];
        foreach ($nav as $key => $value) {
            $items[] = array_merge($value, [
                'children' => $this->getChildrenReply($value['reply_id'])
            ]);
        }
        return $items;
    }

    public function deleteReply(string $replyId, string $form_id): Response
    {

        $reply = $this->where([
            'reply_id' => $replyId
        ]);

        $info = $reply -> findOrEmpty();

        // 减去主表评论数量
        if ($info -> isEmpty()) return message() -> nodata('需要删除的评论不存在');
        $dec = (new modelData())
            -> setFormId($form_id)
            -> modelFieldIncOrDec('reply_count', $info['col_uuid'], 1, 'dec');

        if (is_string($dec)) return message() -> parameter_error($dec);

        $delete = $reply -> delete();

        if ($delete) {
            $this->where([
                'parent_id' => $replyId
            ]) -> delete();
            return message() -> success('删除成功');
        }
        return message() -> update_failed('删除失败');
    }

}